import { udp } from '@cscec/udp-ui';
import { encodeParams } from '../common';
import template from '../portal/template';
import { ENUM_TEMPLATE, LIST_TREE_TYPE, EDIT_DISPLAY_TYPE } from './data';

/**
 * 获取表列元数据信息
 */
export async function getTableFields() {
  const bizCode = udp.getQueryValue('bizCode') || udp.getQueryValue('busType');
  if (!bizCode) { return []; }
  const { code, message, data } = await udp.request.get({
    url: '/engine/metadata/dataModelDesign/queryBizTableListByBizCode',
    data: { bizCode },
  });
  if (code === 0) {
    return data || [];
  }
  udp.alert(message);
  return [];
}

/**
 * 根据url的id获取设计器数据
 */
export async function getDesignContent(id?: string) {
  id = id || udp.getQueryValue('id');
  if (!id) { return {}; }
  const { code, message, data } = await udp.request.get({
    // url: '/engine/metadata/formModelDesign/queryFormModelDesignById',
    url: '/engine/metadata/formModelDesign/newQueryFormModelDesignById',
    data: { id },
  });
  if (code === 0) {
    return data ? {
      listInfo: udp.parseJson(data.listInfo),
      editInfo: udp.parseJson(data.editInfo),
      jsInfo: data.jsInfo,
      recordVer: data.recordVer,
      schemeName: data.schemeName,
      id: data.id,
      formType: data.formType,
      capacity:{
        bizFlowFlag: data.bizFlowFlag || 0,
        bizRuleFlag: data.bizRuleFlag || 0,
        metricsFlag: data.metricsFlag || 0,
        policyShareFlag: data.policyShareFlag || 0,
      },
      templateInfo: {
        listLayout: data.listLayout || ENUM_TEMPLATE.NULL,
        editLayout: data.editLayout || ENUM_TEMPLATE.NULL,
        listTreeType: data.listTreeType || LIST_TREE_TYPE.PROJECT,    //树类型
        editDisplayType: data.editDisplayType || EDIT_DISPLAY_TYPE.PANEL,   //详情页展示类型
      },
    } : {};
  }
  udp.alert(message);
  return {};
}

// 保存设计器内容
export async function saveDesign(params: IDesignParams) {
  const { code, message } = await udp.request.body({
    // url: '/engine/metadata/formModelDesign/saveOrUpdateFormDesignerDesign',
    url: '/engine/metadata/formModelDesign/newSaveOrUpdateFormDesignerDesign',
    data: encodeParams(params),
  });
  if (code === 0) {
    udp.message('保存成功！', 'success');
    return true;
  }
  udp.alert(message);
  return false;
}

// 发布设计器内容
export async function publishDesign(params: IDesignParams) {
  const { code, message: msg, data } = await udp.request.body({
    url: '/engine/metadata/formModelDesign/publishCustomFormDesign',
    data: encodeParams(params),
  });
  if (code === 0) {
    udp.message('发布成功！', 'success');
    return true;
  }
  msg && udp.alert(msg);
  return false;
}

interface IDesignParams {
  id: string;
  listInfo: object;
  editInfo: object;
  jsInfo: string;
  recordVer: number;
  bizCode: string;
}
